﻿using System;
using System.IO;
using System.Net;

namespace easytodowebclient.Helpers
{
    public class HttpRequester
    {
        private WebResponse _response;
        private HttpWebRequest _request;
        private readonly Uri _uri;

        public HttpRequester(string requestUriString)
            : this(new Uri(requestUriString))
        { }

        public HttpRequester(Uri requestUri)
        {
            _uri = requestUri;
        }

        public string GetResponse()
        {
            string response;

            try
            {

                if (_response == null)
                {
                    MakeRequest("application/json");
                }

                response = ReadResponseStream();
            }
            catch (Exception)
            {
                throw new WebException("There was an error with the request, please try later.");
            }

            return response;
        }

        public string GetXmlResponse()
        {
            string response;

            try
            {

                if (_response == null)
                {
                    MakeRequest("application/xml");
                }

                response = ReadResponseStream();
            }
            catch (Exception)
            {
                throw new WebException("There was an error with the request, please try later.");
            }

            return response;
        }

        private string ReadResponseStream()
        {
            string response = string.Empty;
            if (_response != null)
            {
                var streamReader = new StreamReader(_response.GetResponseStream());

                response = streamReader.ReadToEnd();

                streamReader.Close();
            }

            return response;
        }

        private void MakeRequest(string accept)
        {
            _request = WebRequest.Create(_uri) as HttpWebRequest;
            _request.Accept = accept;
            _response = _request.GetResponse();
        }
    }
}